package cn.onecloud.tablet.xiaozhi;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.freerdp.freerdpcore.presentation.SessionActivity;
import com.freerdp.freerdpcore.utils.Log;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import cn.onecloud.tablet.xiaozhi.model.DesktopInfo;
import cn.onecloud.tablet.xiaozhi.net.FeedBackAppc;
import cn.onecloud.tablet.xiaozhi.net.WSResult;
import cn.onecloud.tablet.xiaozhi.net.WSThread;
import cn.onecloud.tablet.xiaozhi.net.WebSocketResult;
import cn.onecloud.tablet.xiaozhi.util.DtoUtils;
import cn.onecloud.tablet.xiaozhi.util.IPUtil;
import cn.onecloud.tablet.xiaozhi.util.NumberUtil;
import cn.onecloud.tablet.xiaozhi.util.TimeUtil;


/**
 * Created by yin.he on 17-11-14.
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener {

    private ImageView imageView;
    private String uqunicode;
    private EditText address;
    private EditText port;
    private EditText domain;
    private EditText username;
    private EditText password;
    private LinearLayout scanCode;
    private LinearLayout inputForm;
    private CheckBox checkBox;

    //使用定时线程而不使用timertask，避免在执行失败后影响后续任务执行
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);

    // 用来定时更新二维码,用来线程间传递信息
    private Handler codeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            uqunicode = TimeUtil.getUUID8();
            WSThread.uuid = uqunicode;
            String loginUrl = "https://appcc.cloudak47.com/s?T=3&k=" + uqunicode + "&t=" + TimeUtil.getSHTime();
            WSThread.getInstance().interrupt();
            if (!WSThread.getInstance().isAlive()) {
                WSThread.getInstance().start();
            }
            Log.i(MainActivity.class.getName(), "qrcode url : " + loginUrl);
            Bitmap bitmap;
            if (WSThread.isConnect) {
                bitmap = CodeUtils.createImage(loginUrl, 200, 200, BitmapFactory.decodeResource(getResources(), R.drawable.logoicon));
            } else {
                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.linkerror);
            }
            imageView.setImageBitmap(bitmap);
            super.handleMessage(msg);
        }
    };

    private Handler loginHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            FeedbackNotify feedbackNotify = new FeedbackNotify();
            feedbackNotify.execute((Void) null);
            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 1:竖屏   2:横屏
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == 1) {
            setContentView(R.layout.activity_portrait_main);
        }
        if (orientation == 2) {
            setContentView(R.layout.activity_lanscape_main);
        }
        scanCode = (LinearLayout) findViewById(R.id.scan_code);
        inputForm = (LinearLayout) findViewById(R.id.input_form);
        imageView = (ImageView) findViewById(R.id.image_content);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message = new Message();
                codeHandler.sendMessage(message);
            }
        });

        address = (EditText) findViewById(R.id.address);
        address.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus == false) {
                    showRemeberMe(v);
                }
            }
        });
        port = (EditText) findViewById(R.id.port);
        domain = (EditText) findViewById(R.id.domain);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        checkBox = (CheckBox) findViewById(R.id.remeber_me);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {

                } else {
                    final String addressTxt = address.getText().toString();
                    if (!TextUtils.isEmpty(addressTxt) && IPUtil.check(addressTxt)) {
                        deleteRemeberMe(addressTxt);
                    }

                }
            }
        });

        Button loginRdp = (Button) findViewById(R.id.loginRdp);
        loginRdp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isInValid = false;
                View focusView = null;
                address.setError(null);
                port.setError(null);
                domain.setError(null);
                username.setError(null);
                password.setError(null);
                final String passwordTxt = password.getText().toString();
                if (TextUtils.isEmpty(passwordTxt)) {
                    password.setError("请输入密码！");
                    focusView = password;
                    isInValid = true;
                }
                final String usernameTxt = username.getText().toString();
                if (TextUtils.isEmpty(usernameTxt)) {
                    username.setError("请输入用户名！");
                    focusView = username;
                    isInValid = true;
                }
                final String domainTxt = domain.getText().toString();
                final String portTxt = port.getText().toString();
                if (TextUtils.isEmpty(portTxt) || !NumberUtil.isNumeric(portTxt)) {
                    port.setError("你输入的端口号不合法！");
                    focusView = port;
                    isInValid = true;
                }
                final String addressTxt = address.getText().toString();
                if (TextUtils.isEmpty(addressTxt) || !IPUtil.check(addressTxt)) {
                    address.setError("你输入的ip不合法！");
                    focusView = address;
                }
                if (isInValid) {
                    focusView.requestFocus();
                    return;
                } else {
                    DesktopInfo desktopInfo = new DesktopInfo();
                    desktopInfo.setIp(addressTxt);
                    desktopInfo.setPort(portTxt);
                    desktopInfo.setDomain(domainTxt);
                    desktopInfo.setUsername(usernameTxt);
                    desktopInfo.setPassword(passwordTxt);
                    if (checkBox.isChecked()) {
                        rememberMe(desktopInfo);
                    }
                    DesktopLoginTask desktopLoginTask = new DesktopLoginTask(desktopInfo);
                    desktopLoginTask.execute((Void) null);
                }
            }
        });
        scheduledExecutorService.scheduleAtFixedRate(new LoginTask("login-ing"), 300, 1000, TimeUnit.MILLISECONDS);
        scheduledExecutorService.scheduleAtFixedRate(new QRCodeTask("qrcode-refresh"), 0, 1000 * 60 * 2, TimeUnit.MILLISECONDS);
    }

    private void showRemeberMe(View view) {
        List<DesktopInfo> desktopInfoList = LoginUserMsg.xmlRead(this.getFilesDir());
        if (null != desktopInfoList && desktopInfoList.size() > 0) {
            for (int i = 0; i < desktopInfoList.size(); i++) {
                DesktopInfo desk = desktopInfoList.get(i);
                if (desk.getIp().equals(address.getText().toString())) {
                    port.setText(desk.getPort());
                    domain.setText(desk.getDomain());
                    username.setText(desk.getUsername());
                    password.setText(desk.getPassword());
                    checkBox.setChecked(true);
                    break;
                }
            }
        }
    }

    public void deleteRemeberMe(String addressTxt) {
        List<DesktopInfo> desktopInfoList = LoginUserMsg.xmlRead(this.getFilesDir());
        for (int i = 0; i < desktopInfoList.size(); i++) {
            if (desktopInfoList.get(i).getIp().equals(addressTxt)) {
                desktopInfoList.remove(i);
                break;
            }
        }
        LoginUserMsg.xmlWrite(desktopInfoList, this.getFilesDir());
    }

    private void rememberMe(DesktopInfo desktopInfo) {
        List<DesktopInfo> exsistUsers = LoginUserMsg.xmlRead(this.getFilesDir());
        for (int i = 0; i < exsistUsers.size(); i++) {
            DesktopInfo desk = exsistUsers.get(i);
            Log.i("user", desk.toString());
            if (desk.getIp().equals(desktopInfo.getIp())) {
                exsistUsers.remove(i);
                break;
            }
        }
        exsistUsers.add(desktopInfo);
        LoginUserMsg.xmlWrite(exsistUsers, this.getFilesDir());
    }

    @Override
    protected void onStart() {
        super.onStart();
        LinearLayout linear = (LinearLayout) findViewById(R.id.header);

        List<Map.Entry<String, DesktopInfo>> list = new ArrayList<>();
        for (Map.Entry<String, DesktopInfo> entry : DtoUtils.getMap().entrySet()) {
            list.add(entry);
        }
        for (int i = 0; i < list.size(); i++) {
            DesktopInfo desktopInfo = list.get(i).getValue();
            Button btn = (Button) linear.getChildAt(i);
            btn.setText(desktopInfo.getUsername() + "\n" + desktopInfo.getIp());
            btn.setTag(desktopInfo.getUsername() + ":" + desktopInfo.getIp());
            btn.setOnClickListener(MainActivity.this);
            btn.setOnLongClickListener(MainActivity.this);
            btn.setAllCaps(false);
            ColorStateList whiteColor = getResources().getColorStateList(R.color.white);
            btn.setTextColor(whiteColor);
            btn.setVisibility(View.VISIBLE);
        }
    }

    public void openLoginFrom(View v) {
        inputForm.setVisibility(View.VISIBLE);
        scanCode.setVisibility(View.GONE);
    }

    public void openMain(View v) {
        inputForm.setVisibility(View.GONE);
        scanCode.setVisibility(View.VISIBLE);
    }

    class QRCodeTask extends Thread {
        public QRCodeTask(String name) {
            super(name);
        }

        @Override
        public void run() {
            Message message = new Message();
            codeHandler.sendMessage(message);
        }
    }


    class LoginTask extends Thread {

        public LoginTask(String name) {
            super(name);
        }

        @Override
        public void run() {
            Message message = new Message();
            loginHandler.sendMessage(message);
        }
    }

    public void loginRdp(DesktopInfo desktopInfo) {
        if (DtoUtils.getMap().size() < 10) {
            DtoUtils.getMap().put(desktopInfo.getUsername() + ":" + desktopInfo.getIp(), desktopInfo);
        }
        String uri = "freerdp://" + desktopInfo.getUsername() + "@" +
                desktopInfo.getIp() + ":" + desktopInfo.getPort() + "/connect?rfx=&p=" + desktopInfo.getPassword() + "&clipboard=%2b&themes=-&microphone=&audio-mode=0&sound=&size=automatic";
        if (!TextUtils.isEmpty(desktopInfo.getDomain())) {
            uri += "&sec=rdp&d=" + desktopInfo.getDomain();
        }
        Log.i(MainActivity.class.getName(), uri);
        Intent intent = new Intent(this, SessionActivity.class);
        Uri data = Uri.parse(uri);
        intent.putExtra(SessionActivity.PARAM_DESKTOP_NAME, desktopInfo.getUsername());
        intent.putExtra(SessionActivity.PARAM_HIDE_STATUS_BAR, false);
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        Map<String, DesktopInfo> map = DtoUtils.getMap();
        System.out.println(v.getTag());
        DesktopInfo desktopInfo = map.get(v.getTag());
        loginRdp(desktopInfo);
    }

    @Override
    public boolean onLongClick(View v) {
        final View view = v;
        new AlertDialog.Builder(MainActivity.this).setTitle("断开桌面").setMessage("确定断开该桌面吗？").setPositiveButton("断开", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                LinearLayout linear = (LinearLayout) findViewById(R.id.header);
                linear.removeView(view);
                String key = (String) view.getTag();
                DtoUtils.getMap().remove(key);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
        return true;
    }

    /**
     * 执行异步登录
     */
    private class DesktopLoginTask extends AsyncTask<Void, Void, Boolean> {

        private DesktopInfo desktopInfo;

        public DesktopLoginTask(DesktopInfo desktopInfo) {
            this.desktopInfo = desktopInfo;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            loginRdp(desktopInfo);
            return true;
        }
    }

    /**
     * 执行异步登录
     */
    private class FeedbackNotify extends AsyncTask<Void, Void, Boolean> {

        private String uuid;

        public FeedbackNotify() {
        }

        public FeedbackNotify(String uuid) {
            this.uuid = uuid;
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            if (WSThread.isScan) {
                WSThread.isScan = false;
            }
            if (WSThread.isLogin) {
                WebSocketResult webSocketResult = WSThread.webSocketResult;
                WSResult wsResult = webSocketResult.getWsResult();
                if ("success".equalsIgnoreCase(wsResult.getResult())) {
                    Log.d(MainActivity.class.getName(), "uuid >>> " + webSocketResult.getUuid());
                    FeedBackAppc.feedbackToAPPCC(webSocketResult.getUuid(), true);
                } else if ("fail".equalsIgnoreCase(wsResult.getResult())) {
                    FeedBackAppc.feedbackToAPPCC(webSocketResult.getUuid(), false);
                } else if ("cancel".equalsIgnoreCase(wsResult.getResult())) {

                } else {

                }
                if (WSThread.isDeskgroup) {
                    if (WSThread.desktopInfoList != null && WSThread.desktopInfoList.size() > 0) {
                        for (DesktopInfo desktopInfo : WSThread.desktopInfoList) {
                            if (DtoUtils.getMap().size() < 10) {
                                DtoUtils.getMap().put(desktopInfo.getUsername() + ":" + desktopInfo.getIp(), desktopInfo);
                            }
                        }
                    }
                    loginRdp(WSThread.desktopInfoList.get(0));
                } else {
                    DesktopInfo desktopInfo = WSThread.desktopInfo;
                    loginRdp(desktopInfo);
                }
            }
            WSThread.isLogin = false;
            WSThread.isDeskgroup = false;

            return true;
        }
    }
}
